//
//  AssetViewController.m
//  DaoZiJinFu
//
//  Created by woker on 16/7/13.
//  Copyright © 2016年 iwoker. All rights reserved.
//

#import "AssetViewController.h"
#import "AssetCell.h"
#import "RechangeCell.h"
#import "AssetHeaderView.h"
#import "RechargeViewController.h"
#import "WithdrawalsViewController.h"
#import "InvestmentTableViewController.h"
#import "TransactionRecordTableVC.h"
#import "CashVoucherTableVC.h"
#import "BindCardTableVC.h"
#import "MyBankCard.h"
#import "SecutyView.h"

@interface AssetViewController () <UITableViewDelegate,UITableViewDataSource> {
    NSArray *titleArray;
    AssetHeaderView *assetHeader;
}

@property (strong, nonatomic) UITableView *assertTableView;
@property (strong, nonatomic) UIScrollView *imgView;

@end

@implementation AssetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTitleView:@"我的资产"];
    self.tabBarItem.title = @"资产";
    self.view.backgroundColor = BACKGROUND_COLOR;
    
    titleArray = @[
                   @[@"在投金额",@"交易记录"],
                   @[@"现金抵用券",@"我的银行卡"]
                   ];
    [theUser synchronize];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rechangeClick) name:@"rechangeCash" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(withdrawalsClick) name:@"withdrawalsCash" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateAssetInformation) name:@"updateAssetInformation" object:nil];
    [self setUpView];
    self.assertTableView.mj_header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadForUserInfo)];
}

- (void)loadForUserInfo {
    DZRequestUtil *request = [[DZRequestUtil alloc] init];
    request.httpMethod = @"GET";
    request.requestUrl = @"User/getUserInfo";
    [DZNetAPI request:request success:^(id response) {
        [_assertTableView.mj_header endRefreshing];
        NSLog(@"%@",response);
        if ([response[@"rt"] integerValue] == 1) {
            [CommTools setUserInfo:response];
            [_assertTableView reloadData];
        }else if ([response[@"rt"] integerValue] == 11){
         
        }else if([response[@"rt"] integerValue] == 0){
            [self getLoginAction];
        }else{
           JSSHOW(response[@"msg"]);
        }
    } failure:^(NSError *error) {
        [_assertTableView.mj_header endRefreshing];
    }];
}

- (void)getLoginAction {
    if (DZUserInfo.userInfo.mobile) {
        DZRequestUtil *request = [[DZRequestUtil alloc] init];
        request.requestUrl = @"Index/login";
        request.params = @{@"mobile":DZUserInfo.userInfo.mobile};
        [DZNetAPI request:request success:^(id response) {
            NSLog(@"%@",response);
            DZResponse *info = [DZResponse mj_objectWithKeyValues:response];
            if (info.rt == 1) {
                if (info.data[@"uInfo"][LOGIN_TOKEN]) {
                    [theUser setObject:info.data[@"uInfo"][LOGIN_TOKEN] forKey:LOGIN_TOKEN];
                }
                [theUser setObject:[NSNumber numberWithBool:YES] forKey:ISLOGIN];
                [CommTools setUserInfo:response];
                _imgView.hidden = YES;
                self.navigationController.navigationBar.hidden = NO;
            }else if(info.rt == 11){
            }else{
                JSSHOW(info.msg);
                [theUser setObject:[NSNumber numberWithBool:NO] forKey:ISLOGIN];
                [CommTools removeAllSet];
                _imgView.hidden = NO;
                self.navigationController.navigationBar.hidden = YES;
            }
            [self.assertTableView reloadData];
        } failure:^(NSError *error) {
        }];
    }
}


- (void)setUpView {
    _assertTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _assertTableView.backgroundColor = BACKGROUND_COLOR;
    _assertTableView.delegate = self;
    _assertTableView.dataSource = self;
    _assertTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_assertTableView];
    [_assertTableView registerNib:[UINib nibWithNibName:@"AssetCell" bundle:nil] forCellReuseIdentifier:ASSET_CELL];
    [_assertTableView registerNib:[UINib nibWithNibName:@"RechangeCell" bundle:nil] forCellReuseIdentifier:RECHANGE_CELL];
    //未登录时显示
    _imgView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _imgView.backgroundColor = [UIColor whiteColor];
    _imgView.showsHorizontalScrollIndicator = NO;
    _imgView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_imgView];
    
    UIImageView *subImg = [[UIImageView alloc] init];
    subImg.image = [UIImage imageNamed:@"资产未登录"];
    CGSize size = subImg.image.size;
    CGFloat imageHeight = SCREEN_WIDTH*size.height/size.width;
    
    
    [_imgView addSubview:subImg];
    
    SecutyView *secutyView = [SecutyView loadView];
    [_imgView addSubview:secutyView];
    
    UIButton *btn = [[UIButton alloc] init];
    [btn setTitle:@"开启赚钱之路" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn setBackgroundImage:IMAGE(@"asset_button") forState:UIControlStateNormal];
    btn.layer.cornerRadius = 10;
    btn.layer.masksToBounds = YES;
    [btn addTarget:self action:@selector(comeInClick) forControlEvents:UIControlEventTouchUpInside];
    [_imgView addSubview:btn];
    
    [subImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_imgView.mas_centerX);
        make.centerY.equalTo(_imgView).with.offset(-80);
        make.height.equalTo(@(imageHeight));
        make.width.mas_equalTo(SCREEN_WIDTH);
    }];
    
    [secutyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_imgView.mas_centerX);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.top.equalTo(subImg.mas_bottom).offset(40);
    }];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_imgView.mas_centerX);
        make.top.equalTo(secutyView.mas_bottom).offset(39);
        make.height.equalTo(@44);
        make.width.equalTo(@(SCREEN_WIDTH - 24));
    }];
    
    _imgView.contentSize = CGSizeMake(SCREEN_WIDTH, imageHeight+24+50+24+44+24+44);
}

// 通知刷新
- (void)updateAssetInformation {
    [self loadForUserInfo];
}


- (void)comeInClick {
    if (userValue(HOSTTEL)) {
        LoginViewController *login = [[LoginViewController alloc] init];
        login.telNum = userValue(HOSTTEL);
        login.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:login animated:YES];
    } else {
        RegisterViewController *join = [[RegisterViewController alloc] init];
        join.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:join animated:YES];
    }
}

- (void)rechangeClick {
    BOOL cardBind = [userValue(ISBINDCARD) boolValue];
    if (!cardBind) {
        BindCardTableVC *bindCard = [[BindCardTableVC alloc] init];
        bindCard.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:bindCard animated:YES];
    } else {
        RechargeViewController *recharge = [[RechargeViewController alloc] init];
        recharge.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:recharge animated:YES];
    }
}

- (void)withdrawalsClick {
    BOOL cardBind = [userValue(ISBINDCARD) boolValue];
    BOOL isDealPwd = [userValue(ISSETDEALPWD) boolValue];
    BOOL isSetBankInfo = [userValue(ISSETBANK) boolValue];
    if (!cardBind) {
        BindCardTableVC *bindCard = [[BindCardTableVC alloc] init];
        bindCard.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:bindCard animated:YES];
    } else if (!isDealPwd) {
        SettingDealPassword *dealPwd = [[SettingDealPassword alloc] init];
        dealPwd.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:dealPwd animated:YES];
    } else if (!isSetBankInfo) {
        SettingBankInfo *bankInfo = [[SettingBankInfo alloc] init];
        bankInfo.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:bankInfo animated:YES];
    } else {
        WithdrawalsViewController *withdrawals = [[WithdrawalsViewController alloc] init];
        withdrawals.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:withdrawals animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!section) {
        return 1;
    } else {
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.section) {
        AssetCell *assetCell = [AssetCell cellWithTableView:tableView];
        assetCell.cellIcon.image = [UIImage imageNamed:titleArray[indexPath.section-1][indexPath.row]];
        assetCell.cellTitle.text = titleArray[indexPath.section-1][indexPath.row];
        if (DZUserInfo.userInfo.total_finance) {
            assetCell.cellSubTitle.text = [NSString stringWithFormat:@"%@",DZUserInfo.userInfo.total_finance];
        }
        assetCell.cellSubTitle.font = [UIFont systemFontOfSize:14];
        if (indexPath.section == 1 && indexPath.row == 0) {
            assetCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            assetCell.cellSubTitle.textColor = ORANGECOLOR;
        } else if (indexPath.section == 1 && indexPath.row == 1) {
            assetCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            assetCell.cellSubTitle.hidden = YES;
        } else if (indexPath.section == 2 && indexPath.row == 0) {
            assetCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            if (DZUserInfo.userInfo.total_coupon) {
                assetCell.cellSubTitle.text = [NSString stringWithFormat:@"%@张可用",DZUserInfo.userInfo.total_coupon];
                assetCell.cellSubTitle.textColor = ORANGECOLOR;
            } else {
                assetCell.cellSubTitle.text = @"";
            }
        } else if (indexPath.section == 2 && indexPath.row == 1) {
            if (DZUserInfo.userInfo.banks) {
                DZBankInfo *bank = [DZBankInfo mj_objectWithKeyValues:[DZUserInfo.userInfo.banks firstObject]];
                if ([bank.certified_status integerValue] == 2) {
                    assetCell.cellSubTitle.text = @"已认证";
                    assetCell.cellSubTitle.textColor = DEFAULTCOLOR;
                }
                else {
                    assetCell.cellSubTitle.text = @"未认证";
                    assetCell.cellSubTitle.textColor = BLUE_COLOR;
                }
            } else {
                assetCell.cellSubTitle.text = @"";
            }
        }
        
        cell = assetCell;
    } else {
        RechangeCell *rechargeCell = [RechangeCell cellWithTableView:tableView];
        cell = rechargeCell;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (!section) {
        return 180;
    }
    return 8;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (!section) {
        NSLog(@"BALANCE:%@",DZUserInfo.userInfo.account_balance);
        assetHeader = [AssetHeaderView loadView];
        if (DZUserInfo.userInfo.total_assets) {
            float money = [DZNsstringUtil floatInto:[DZUserInfo.userInfo.total_assets doubleValue]];
            assetHeader.allMoney.text = [NSString stringWithFormat:@"%.2lf",money];
        }
        if (DZUserInfo.userInfo.account_balance) {
            float money = [DZNsstringUtil floatInto:[DZUserInfo.userInfo.account_balance doubleValue]];
            assetHeader.useableMoney.text = [NSString stringWithFormat:@"%.2lf",money];
        }
        if (DZUserInfo.userInfo.total_gains_amount) {
            float money = [DZNsstringUtil floatInto:[DZUserInfo.userInfo.total_gains_amount doubleValue]];
            assetHeader.allIncome.text = [NSString stringWithFormat:@"%.2lf",money];
        }
        return assetHeader;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIViewController *vc;
    if (indexPath.section == 1) {
        if (!indexPath.row) {
            InvestmentTableViewController *investment = [[InvestmentTableViewController alloc] init];
            vc = investment;
        } else if (indexPath.row == 1) {
            TransactionRecordTableVC *transactionRecord = [[TransactionRecordTableVC alloc] init];
            vc = transactionRecord;
        }
    } else if (indexPath.section == 2) {
        if (!indexPath.row) {
            CashVoucherTableVC *cashVoucher = [[CashVoucherTableVC alloc] init];
            vc = cashVoucher;
        } else if (indexPath.row == 1) {
            if ([userValue(ISBINDCARD) boolValue] == YES) {
                MyBankCard *bankCard = [[MyBankCard alloc] init];
                vc = bankCard;
            } else {
                BindCardTableVC *bindCard = [[BindCardTableVC alloc] init];
                vc = bindCard;
            }
        }
    }
    if (vc) {
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([userValue(ISLOGIN) boolValue] == NO) {
        _imgView.hidden = NO;
        self.navigationController.navigationBar.hidden = YES;
        [self getLoginAction];
    } else {
        _imgView.hidden = YES;
        [self loadForUserInfo];
        self.navigationController.navigationBar.hidden = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

@end
